<?php


namespace App\Http\Controllers\Wx;


use App\CodeResponse;
use App\Models\Address;
use App\Services\AddressServices;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;

class AddressController extends WxController
{
    /**
     * 获取用户地址列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function list()
    {
        $list = AddressServices::getInstance()->getAddressByUserId();
        $list = $list->map(function (Address $address){
           $address = $address->toArray();
           $item = [];
           foreach ($address as $key => $value){
               $key = lcfirst(Str::studly($key));
               $item[$key] = $value;
           }
           return $item;
        });
        return $this->success([
            'total'=>$list->count(),
            'page'=>1,
            'list'=>$list->toArray(),
            'pages'=>1,
            'limit'=>$list->count(),
        ]);
    }

    /**
     * 收货地址详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $addressId = $request->input('address');
        if(empty($addressId)){
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $address = AddressServices::getInstance()->query($this->user()->id,$addressId);
        if (is_null($address)){
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        return $this->success($address);
    }

    public function save(Request $request)
    {
        $addressId = $request->input('address');
        if(empty($addressId)){
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $id =  $request->input('id',0);
        if(empty($id) && !is_numeric($id)){
            if (true) {
                // 重置其他收货地址的默认选项
                AddressServices::getInstance()->resetDefault(userId);
            }


        }else{
            $address = AddressServices::getInstance()->query($this->user()->id,$addressId);
            if($address == null){
                return $this->fail(CodeResponse::PARAM_ILLEGAL);
            }
        }

    }

    /**
     * 地址删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request)
    {
        $id =  $request->input('id',0);
        if(empty($id) && !is_numeric($id)){
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        AddressServices::getInstance()->delete($this->user()->id,$id);
        return  $this->success();
    }
}
